<template>
    <div>
        <div class="search">
            <input v-model="keyword" type="text" placeholder="请输入要搜索的内容">
        </div>
        <div 
            class="search-content" 
            ref="search"
            v-show="keyword"
        >
            <ul>
                <li 
                    v-for="item of list" 
                    :key="item.id"
                    @click="handleCityClick(item.name)"
                >
                    {{item.name}}
                </li>
                <li v-show="hasNoData">
                    没有找到匹配的数据
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
import BetterScroll from 'better-scroll' 

export default {
    name:"Search",
    props :{
        cities:Object
    },
    data () {
        return {
            keyword:'',
            list:[],
            timer:null
        }
    },
    computed:{
        hasNoData(){
            return !this.list.length;
        }
    },
    watch:{
        keyword () {
            if(this.timer){
                clearTimeout(this.timer)
            }
            if(!this.keyword){
                this.list = [];
                return;
            }
            this.timer = setTimeout( () => {
                const result = []
                for(let i in this.cities){
                    this.cities[i].forEach((value) => {
                        if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
                            result.push(value)
                        }
                    })
                }
                this.list = result;
            },100)
        }
    },
    methods:{
        handleCityClick(city){
            this.$store.dispatch('changeCity',city)
            this.$router.push('/')
        }
    },
    mounted (){
        this.scroll = new BetterScroll(this.$refs.search, {
            movable: false, 
            zoom: false
        })
    }
}
</script>

<style lang="less" scoped>
.search{
    width: 100%;
    height: .8rem;
    background: #00bcd4;
    padding: .1rem .1rem;
    display: flex;
    justify-content: center;
    align-items: center;
    box-sizing: border-box;
    input{
        width: 100%;
        height: .6rem;
        display: block;
        border: none;
        outline: none;
        background: #fff;
        border-radius: .1rem;
        padding: 0 .1rem;
        box-sizing: border-box;
    }
}
.search-content{
    width: 100%;
    z-index: 2;
    overflow: hidden;
    position: absolute;
    top: 1.58rem;
    left: 0;
    right: 0;
    bottom: 0;
    background: #eee;
    font-size: .28rem;
    ul{
        li{
            line-height: .62rem;
            padding-left: .2rem;
            background: #fff;
            color: #666;
            border-bottom: 1px solid #ddd;
        }
        :last-child{
            border-bottom: none;
        }
    }
    
}
</style>